package jmu.edu.yjc.Utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class PathUtils {
    public static String generateFilePath(MultipartFile img,String fileName) throws IOException {
        //根据日期生成路径   2022/1/15/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //uuid作为文件名
//        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String id = md5(img.getBytes());
        //后缀和文件后缀一致
        int index = fileName.lastIndexOf(".");
        // test.jpg -> .jpg
        String fileType = fileName.substring(index);
        return new StringBuilder().append(datePath).append(id).append(fileType).toString();
    }

    public static String md5(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            return byteArrayToString(md.digest(data));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    //根据字节码变成唯一id
    public static String byteArrayToString(byte[] b) throws UnsupportedEncodingException {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToNumString(b[i]));
        }
        return new String(resultSb.toString().getBytes(), StandardCharsets.UTF_8);
    }
    //字节转数字
    private static String byteToNumString(byte b) {
        int _b = b;
        if (_b < 0) {
            _b = 256 + _b;
        }
        return String.valueOf(_b);
    }
}
